package com.quanyan.comment.service.impl;

import com.google.common.base.Function;
import com.google.common.collect.ImmutableMultiset;
import com.google.common.collect.Lists;
import com.quanyan.comment.cache.MyRedisTemplate;
import com.quanyan.comment.mapper.TbSensitiveMapper;
import com.quanyan.comment.model.constant.Constants;
import com.quanyan.comment.model.po.TbSensitive;
import com.quanyan.comment.sensitive.DFAWordFilter;
import com.quanyan.comment.sensitive.NodeTree;
import com.quanyan.comment.service.SensitiveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 *
 */
@Service
public class SensitiveServiceImpl implements SensitiveService {


	@Autowired
	private MyRedisTemplate myRedisTemplate;

	@Autowired
	private TbSensitiveMapper tbSensitiveMapper;

	public DFAWordFilter getDfaWordFilter(){
		return new DFAWordFilter(NodeTree.getNoteTree(this.getSensitiveString()));
	}

	@Override
	public String filter(String str, String replacement) {
		return getDfaWordFilter().filterKeyWord$Script(str, replacement);
	}

	@Override
	public boolean isExistsKey(String str) {
		return  getDfaWordFilter().isExistsKey(str);
	}

	public List<TbSensitive>  getSensitive(){
		List<TbSensitive> tbSensitiveList = (List<TbSensitive>)myRedisTemplate.get(Constants.SENSITIVE_KEY);
		if (tbSensitiveList == null){
			tbSensitiveList = tbSensitiveMapper.selectByExample(null);
			myRedisTemplate.set(Constants.SENSITIVE_KEY,tbSensitiveList);
		}
		return tbSensitiveList;
	}

	public List<String> getSensitiveString(){
		List<TbSensitive> tbSensitiveList =this.getSensitive();
		List<String> listSensitive = new ArrayList<>();
		if (tbSensitiveList != null)
			listSensitive = this.getSensitiveToString(tbSensitiveList).asList();
		return listSensitive;
	}

	//list 按属性生成一个新的 list
	public ImmutableMultiset<String> getSensitiveToString(List<TbSensitive> list) {
		return ImmutableMultiset.copyOf(Lists.transform(list, new Function<TbSensitive, String>() {
					@Override
					public String apply(TbSensitive input) {
						return input.getText();
					}
				}
		));
	}



}
